#module  pip install xxx
import os
import face_recognition
import numpy as np
import shutil
import cv2
import re
import string

import random
#file
import mysql_search_write
def huidu_image(patch): 
    #读取源图像
    img = cv2.imread(r"./%s"%filename)
    #img2为灰度图
    img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # cv2.imshow('img2', img2)
    #替换原图
    cv2.imwrite(patch, img2)
    # cv2.waitKey(0) 


def imfile_facedata(sno,filename):
    try:
        png_path="./%s"%filename
        print(png_path)
        huidu_image(png_path)
        picture_of_me = face_recognition.load_image_file(png_path)#加载图片
        # print(face_recognition.face_encodings(picture_of_me))
        my_face_encoding = face_recognition.face_encodings(picture_of_me)[0]
        map=my_face_encoding # 人脸模板,返回图像中每个人脸的128脸部编码（特征向量）。
        # print(map)
    except:
        print("人脸检测失败",sno)
    try:
        path = "./human_face/%s/"%sno
        if not os.path.exists(path):
            os.makedirs(path)
        np_path="./human_face/%s/2.npy"%sno #人脸模板文件
        np.save(np_path,map)# 保存
        shutil.move(png_path,'./human_face/%s/%s'%(sno,filename))
        return 0
    except:
        print("写入模板文件失败")
        return -1

def mysql_operation(filename):
    sno=re.sub(u"([^\u0030-\u0039])","",filename)#读取数字部分
    print("sno",sno)
    sname=re.sub(u'([^\u4e00-\u9fa5])','',filename)#读取汉字部分
    print("sname",sname)
    sroot=1
    spasswd=random.randint(1000, 9999) 
    print("spasswd",spasswd)
    mysql_search_write.mysql_add_Student(sno,sname,sroot,spasswd)
    return sno



if __name__ == '__main__':
    path = "./"
    datanames = os.listdir(path)
    list = []
    for filename in datanames:
        #处理png，jpg两种格式
        if filename.find('.jpg')!=-1:
            sno=mysql_operation(filename)
            imfile_facedata(sno,filename)

        if  filename.find('.png')!=-1:
            sno=mysql_operation(filename)
            imfile_facedata(sno,filename)

